package Veterinaria.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import Veterinaria.excepcion.DAOExcepcion;
import Veterinaria.modelo.Doctor;
import Veterinaria.modelo.Paciente;
import Veterinaria.negocio.GestionPaciente;
import Veterinaria.negocio.GestionPersona;

/**
 * Servlet implementation class BuscaDoctorServlets
 */
@WebServlet("/BuscaDoctorServlets")
public class BuscaDoctorServlets extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public BuscaDoctorServlets() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		PrintWriter out = response.getWriter();
		response.setContentType("text/html");
		response.setHeader("Cache-control", "no-cache, no-store");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Expires", "-1");

		JSONArray arrayObj = new JSONArray();
		JSONObject obj1 = new JSONObject();
		GestionPersona persona = new GestionPersona();
		String nom = null;

		try {
			String query = request.getParameter("term");
			query = query.toLowerCase();

			Collection<Doctor> doctores = persona.ListaDoctorXNombre(query);

			for (Doctor doc : doctores) {
				if (doc.getApellido_persona().toLowerCase().startsWith(query))
					nom = doc.getApellido_persona() + " "
							+ doc.getNombre_persona();
				obj1.put("label", nom);
				obj1.put("value", nom);
				obj1.put("id", doc.getCodigo_persona());

				arrayObj.add(obj1.toString());
				obj1.clear();
			}
		} catch (DAOExcepcion e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			out.println(arrayObj);
			out.close();
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
